<template>
  <div class="container">
    <header class="header-wrap">
      <h3 v-if="$route.query && $route.query.activityId" class="title">编辑在线课程</h3>
      <h3 v-else class="title">发布在线课程</h3>
    </header>
    <outer-box title="在线课程信息">
      <el-form ref="liveForm" :rules="rules" class="liveForm" :model="liveForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="liveForm.title" placeholder="请输入" />
        </el-form-item>

        <el-form-item v-if="list">
          <category
            :list="list"
            biz-type-enum="WEB_CAST"
            :disabled="$route.query && $route.query.activityId ? true : false"
            :gutter="20"
            @Callback="categoryCallback"
          />
        </el-form-item>

        <el-form-item v-if="liveForm.categorySelect" label="分类" prop="categorySelect">
          <el-cascader
            v-model="liveForm.categorySelect"
            filterable
            :options="classifyList"
            :props="{
              multiple: true,
              checkStrictly: true,
              label: 'tagsName',
              value: 'tagsId',
              children: 'sub'
            }"
            clearable
            @blur.native.capture="getAddCategoryTags($event, 'category')"
            @keyup.enter.native=" getAddCategoryTags($event, 'category')"
          />
        </el-form-item>

        <el-form-item v-if="liveForm.tagSelect" label="标签" prop="tagSelect">
          <el-cascader
            v-model="liveForm.tagSelect"
            filterable
            :options="tagsList"
            :props="{
              multiple: true,
              checkStrictly: true,
              label: 'tagsName',
              value: 'tagsId',
              children: 'sub'
            }"
            clearable
            @blur.native.capture="getAddCategoryTags($event, 'tag')"
            @keyup.enter.native=" getAddCategoryTags($event, 'tag')"
          />
        </el-form-item>

        <el-form-item label="时间" prop="time">
          <el-date-picker
            v-model="liveForm.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="$route.query && $route.query.activityId ? true : false"
          />
        </el-form-item>
      </el-form>
    </outer-box>

    <outer-box title="上传封面图片">
      <el-form ref="liveForm2" :rules="rules" class="liveForm" :model="liveForm" label-width="80px">
        <el-form-item label=" " prop="coverImg">
          <el-upload
            class="avatar-uploader"
            :action="action"
            :header="uploadHeader"
            :data="uploadForm"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
          >
            <div v-if="liveForm.coverImg" class="uploader">
              <img :src="liveForm.coverImg" class="avatar" />
            </div>
            <div v-else class="avatar-uploader-content">
              <i class="el-icon-plus" />
              <p>上传封面图片</p>
              <p>只支持jpg/png格式，不超过2m</p>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
    </outer-box>

    <outer-box title="在线课程介绍">
      <el-form ref="liveForm3" :rules="rules" class="liveForm" :model="liveForm" label-width="80px">
        <el-form-item label=" " prop="atvDescribe">
          <editor v-model="liveForm.atvDescribe" @input="introContent" />
        </el-form-item>
      </el-form>
    </outer-box>

    <el-button>预览</el-button>
    <el-button type="primary" @click="_createWebCast">发布</el-button>
  </div>
</template>

<script>
import { preUpload } from '@/api/uploads'
import outerBox from '@/components/outerBox'
import {
  createWebCast,
  updateWebCast,
  cateTagsGroupFindList,
  findColumnList
} from '@/api/webCast'
import editor from '@/components/Tinymce/index'
import category from '@/components/Category'
import { getTagsItems, getParents } from '@/utils/categoryOrTags'
import { webCastDetail } from '@/api/activity'
export default {
  components: {
    outerBox,
    editor,
    category
  },
  data () {
    return {
      action: 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadHeader: {
        'Content-Type': 'multipart/form-data'
      },
      uploadForm: {},
      liveForm: {
        title: '',
        categoryList: [],
        categorySelect: null,
        tagList: [],
        enrollFee: null,
        quota: null,
        tagSelect: null,
        time: [],
        userIdList: null,
        coverImg: '',
        atvDescribe: ''
      },
      rules: {
        title: [{ required: true, message: '请输入在线课程标题', trigger: 'blur' }],
        categorySelect: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个活动性质',
            trigger: 'change'
          }
        ],
        tagSelect: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个标签',
            trigger: 'change'
          }
        ],
        time: [
          {
            type: 'array',
            required: true,
            message: '请选择在线课程时间',
            trigger: 'change'
          }
        ],
        coverImg: [
          { required: true, message: '请上传在线课程封面', trigger: 'change' }
        ],
        atvDescribe: [
          { required: true, message: '请输入在线课程介绍', trigger: 'blur' }
        ]
      },
      classifyList: [],
      categoryFake: [], // 区分自定义标签
      tagsFake: [], // 区分自定义标签
      tagsList: [],
      params: '',
      list: null
    }
  },
  created () {
    if (this.$route.query && this.$route.query.activityId) {
      this.getWebCastDetail()
    } else {
      this.list = {
        GROWTH_CLASSIFY: {
          cateId: '',
          itemCode: '',
          itemName: ''
        },
        STAGE: {
          cateId: '',
          itemCode: '',
          itemName: ''
        },
        SUBJECT: {
          cateId: '',
          itemCode: '',
          itemName: ''
        }
      }
    }
    // this.getCateTagsFindList()
  },
  methods: {
    getAddCategoryTags (el, name) {
      var str = el.target.value
      str = str.replace(/\s|，/g, ',')
      str = str.split(',')
      var arr = str.filter(item => item !== '' && item !== ' ')
      var newArr = []
      arr.map(item => {
        newArr.push({
          tagsId: item,
          tagsName: item
        })
      })

      if (name === 'category') {
        this.liveForm.categorySelect = this.liveForm.categorySelect.concat(arr)
        this.classifyList = this.classifyList.concat(newArr)
        this.categoryFake = this.categoryFake.concat(arr)
      }
      if (name === 'tag') {
        this.liveForm.tagSelect = this.liveForm.tagSelect.concat(arr)
        this.tagsList = this.tagsList.concat(newArr)
        this.tagsFake = this.tagsFake.concat(arr)
      }
      console.log('categoryFake:', this.categoryFake)
      console.log('tagsFake:', this.tagsFake)
    },
    // 获取详情
    getWebCastDetail () {
      webCastDetail(this.$route.query.activityId).then(res => {
        res.data.time = [res.data.createTime, res.data.endTime]

        this.list = {
          GROWTH_CLASSIFY: res.data.teachingTarget,
          STAGE: res.data.phase,
          SUBJECT: res.data.subject
        }
        console.log('this.tagsList：', this.tagsList)

        this.liveForm = res.data
      })
    },
    uploadSuccess (res, file) {
      console.log('上传成功:', URL.createObjectURL(file.raw))
      this.liveForm.coverImg = this.filesUrl
    },
    beforeUpload (file) {
      const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/
      if (!imgStr.test(file.name)) {
        this.$message.error('上传格式不对，请重新上传!')
        return
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return
      }
      let continueUpload = false
      return new Promise((resolve, reject) => {
        preUpload({
          biz: 'OPEN',
          name: file.name,
          size: file.size
        })
          .then(res => {
            this.action = res.data.action
            this.uploadForm = res.data.parameters
            this.filesUrl = res.data.uri
            continueUpload = true
            resolve(continueUpload)
          })
          .catch(err => {
            reject(continueUpload)
          })
      })
    },

    categoryCallback (obj) {
      // console.log('obj', obj)
      this.params = obj

      this.getFindColumnList()
      this.getCateTagsGroupFindList()
    },

    async getCateTagsGroupFindList () {
      const params = {
        growthClassify: this.params.GROWTH_CLASSIFY.itemCode,
        stageId: this.params.STAGE.itemCode,
        subjectId: this.params.SUBJECT.itemCode,
        tagsBizEnum: 'WEB_CAST'
      }
      const res = await cateTagsGroupFindList(params)

      // var op = reduceArr(res.data)
      // var arr = []

      // this.liveForm.tagList.map(item => {
      //   if (item.tagList instanceof Array) {
      //     arr = arr.concat(item.tagList)
      //   }
      // })
      // arr.map(item => {
      //   var items = op.filter(it => it.tagsId === item.tagsId)
      //   if (items.length <= 0) {
      //     res.data.push(item)
      //   }
      // })

      var newArr = []
      res.data.map(item => {
        item.tagsId = item.groupId
        item.tagsName = item.groupName
        item.sub = item.tagsVoList
        if (item.tagsVoList instanceof Array) {
          newArr = newArr.concat(item.tagsVoList)
        }
      })

      // this.tagsList = newArr
      this.tagsList = res.data
      var tagsList = []
      console.log('tagsList:', this.tagsList)

      if (this.liveForm.tagList && this.liveForm.tagList.length > 0) {
        this.liveForm.tagList.map(item => {
          if (item.tagList && item.tagList.length > 0) {
            item.tagList.map(tags => {
              console.log('tags:', tags.tagsName, tags.tagsId)
              if (getParents(this.tagsList, tags.tagsId, 'tagsId') !== undefined) {
                console.log('tags.tagsId:', tags.tagsId, getParents(this.tagsList, tags.tagsId, 'tagsId').reverse())
                tagsList.push(getParents(this.tagsList, tags.tagsId, 'tagsId').reverse())
              }
            })
          }
        })
      }

      this.$set(this.liveForm, 'tagSelect', tagsList)
      // this.liveForm.tagSelect = tagsList
    },

    async getFindColumnList () {
      const params = {
        growthClassify: this.params.GROWTH_CLASSIFY.itemCode,
        stageId: this.params.STAGE.itemCode,
        subjectId: this.params.SUBJECT.itemCode
      }
      const res = await findColumnList(params)
      // var op = reduceArr(res.data)
      // var arr = []
      // this.liveForm.categoryList.map(item => {
      //   if (item.tagList instanceof Array) {
      //     arr = arr.concat(item.tagList)
      //   }
      // })
      // arr.map(item => {
      //   var items = op.filter(it => it.tagsId === item.tagsId)
      //   if (items.length <= 0) {
      //     res.data.push(item)
      //   }
      // })
      this.classifyList = res.data
      var categoryList = []
      if (this.liveForm.categoryList && this.liveForm.categoryList.length > 0) {
        this.liveForm.categoryList.map(item => {
          if (item.tagList && item.tagList.length > 0) {
            item.tagList.map(tags => {
              if (getParents(this.classifyList, tags.tagsId, 'tagsId') !== undefined) {
                categoryList.push(getParents(this.classifyList, tags.tagsId, 'tagsId').reverse())
              }
            })
          }
        })
      }

      this.$set(this.liveForm, 'categorySelect', categoryList)
      // this.liveForm.categorySelect = categoryList
    },

    _createWebCast () {
      this.$refs['liveForm'].validate(valid => {
        if (valid) {
          this.$refs['liveForm2'].validate(valid => {
            if (valid) {
              this.$refs['liveForm3'].validate(valid => {
                if (valid) {
                  // 分类

                  var categoryList = []
                  if (
                    this.liveForm.categorySelect &&
                    this.liveForm.categorySelect.length > 0
                  ) {
                    var categorySelect = getTagsItems(this.liveForm.categorySelect, this.classifyList)
                    categorySelect.map(item => {
                      categoryList.push({
                        tagId: item.tagsId,
                        tagName: item.tagsName
                      })
                    })
                  }

                  // 区分自定义标签
                  categoryList.map(item => {
                    this.categoryFake.filter((fake, inx) => {
                      if (fake === item.tagName) {
                        item.tagId = ''
                      }
                    })
                  })

                  var tagList = []
                  // 标签
                  if (
                    this.liveForm.tagSelect &&
                    this.liveForm.tagSelect.length > 0
                  ) {
                    var tagSelect = getTagsItems(this.liveForm.tagSelect, this.tagsList)

                    tagSelect.map(item => {
                      tagList.push({
                        tagId: item.tagsId,
                        tagName: item.tagsName
                      })
                    })
                  }

                  // 区分自定义标签
                  tagList.map(item => {
                    this.tagsFake.filter((fake, inx) => {
                      if (fake === item.tagName) {
                        item.tagId = ''
                      }
                    })
                  })

                  const params = {
                    activityId:
                      this.$route.query && this.$route.query.activityId
                        ? this.$route.query.activityId
                        : null,
                    atvDescribe: this.liveForm.atvDescribe,
                    categoryList: categoryList,
                    coverImg: this.liveForm.coverImg,
                    endTime: this.liveForm.time[1],
                    enrollFee: this.liveForm.enrollFee,
                    phase: this.params.STAGE.itemCode,
                    quota: this.liveForm.quota,
                    startTime: this.liveForm.time[0],
                    subject: this.params.SUBJECT.itemCode,
                    tagList: tagList,
                    teachingTarget: this.params.GROWTH_CLASSIFY.itemCode,
                    title: this.liveForm.title,
                    userIdList: this.liveForm.userIdList,
                    webCastType: 'WEB_CAST'
                  }

                  if (this.$route.query && this.$route.query.activityId) {
                    // 更新
                    updateWebCast(params).then(res => {
                      this.$message({
                        message: '更新成功',
                        type: 'success'
                      })
                      this.$router.push({
                        path: '/activity/activity',
                        query: {
                          activeTabName: 'Live'
                        }
                      })
                    })
                  } else {
                    // 新增
                    createWebCast(params).then(res => {
                      this.$message({
                        message: '成功新建在线课程',
                        type: 'success'
                      })
                      this.$router.push({
                        path: '/activity/activity',
                        query: {
                          activeTabName: 'Live'
                        }
                      })
                    })
                  }
                } else {
                  console.log('error submit!!')
                  return false
                }
              })
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    introContent (newVal) {
      console.log('newVal:', newVal)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 0 40px;
  .header-wrap {
    .title {
      font-size: 20px;
      color: #000;
      line-height: 124px;
      height: 124px;
    }
  }
}

/deep/.el-form-item {
  width: 700px;
}
/deep/.el-cascader {
  width: 620px;
}
/deep/.el-date-editor {
  width: 620px;
}
.avatar-uploader {
  width: 480px;
  height: 270px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-content {
  color: #8c939d;
  width: 480px;
  height: 270px;
  text-align: center;
  padding-top: 100px;
  i {
    font-size: 28px;
  }
}

.uploader {
  width: 100%;
  height: 100%;
  .avatar {
    max-width: 100%;
    max-height: 100%;
  }
}
</style>
